package com.guigu.eduorder.controller;



import com.google.gson.Gson;
import com.guigu.eduorder.entity.Ab_user;
import com.guigu.eduorder.service.Ab_userService;
import com.guigu.eduorder.util.ConstantWeChat;
import com.guigu.eduorder.util.HttpClientUtils;
import com.guigu.eduorder.util.MD5;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Random;

@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {


    @Autowired
    private Ab_userService ab_userService;

    @GetMapping("callback") //locahost:8085
    public Ab_user callback(String code,String state){
        System.out.println(code);
        System.out.println(state);
        System.out.println("你来啊里么");
        try {
            //向认证服务器发送请求换取access_token

            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";


            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWeChat.WX_OPEN_APP_ID,
                    ConstantWeChat.WX_OPEN_APP_SECRET,
                    code);

            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //把accessTokenInfo字符串转成map集合，根据map里面key获取值
            //使用json转换Gson
            Gson gson = new Gson();
            HashMap hashMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) hashMap.get("access_token");
            String openid = (String) hashMap.get("openid");


            //把扫描到的信息添加到数据库中
            Ab_user ab_user= ab_userService.getOpenIdMember(openid);
            if (ab_user == null){ //ab_user==null，表中没有相同的微信数据，我们进行添加

                        //访问微信的资源服务器，获取用户信息
                        String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                                "?access_token=%s" +
                                "&openid=%s";

                        //拼接两个参数
                        String userInfoUrl = String.format(
                                baseUserInfoUrl,
                                access_token,
                                openid
                        );

                        //发送请求
                        String userInfo=HttpClientUtils.get(userInfoUrl);
                        System.out.println("userInfo："+userInfo);
                        //获取返回userInfo字符串扫码人信息
                        HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                        String nickname = (String) userInfoMap.get("nickname");//昵称
                        String headimgurl = (String) userInfoMap.get("headimgurl");//头像
                        System.out.println("nickname:"+nickname);
                        System.out.println("headimgurl:"+headimgurl);
                        Ab_user abUser = new Ab_user();

                        int radom = new Random().nextInt(999999);
                        if (radom < 100000) {
                            radom += 100000;
                        }
                        String s = MD5.MD5(radom+"");//MD5加密密码
                        System.out.println("openid:"+openid);
                        abUser.setOpenid(openid);
                        abUser.setUsername(nickname);
                        abUser.setTouxiang(headimgurl);
                        abUser.setSalt(s);
                        int insertuser = ab_userService.insertuser(abUser);
                        System.out.println(insertuser);
                        System.out.println(abUser);
                        return abUser;

            }
            //最后一步，返回首页面

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    //1. 生成微信扫码二维码
    @GetMapping("/login") //192.10
    public String getWxcode(){
        System.out.println(22222);
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
        "?appid=%s" +
        "&redirect_uri=%s" +
        "&response_type=code" +
        "&scope=snsapi_login" +
        "&state=%s" +
        "#wechat_redirect";

        String redirectUrl =ConstantWeChat.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl= URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //拼接三个参数 ：id  秘钥 和 code值
        String url = String.format(
                baseUrl,
                ConstantWeChat.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu"
        );
        System.out.println(url);
        //请求这个拼接好的地址，得到返回两个值 accsess_token 和 openid
        //使用httpclient发送请求，得到返回结果
        //String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
        // 请求微信地址
        return "redirect:"+url;
    }
}
